<!-- 作者:高翔宇 时间:2024/4/29 周一 下午1:23 -->
<script setup lang="ts">
import {reactive, ref} from 'vue'
import {Lock, Right, SuccessFilled, User} from "@element-plus/icons-vue";
import type {FormModel} from "@/api/user/type.ts";
import {useUserStore} from "@/store";
import {router} from "@/router";
import {getTimeOfDay} from "@/utils/time.ts";
import {ElMessage} from 'element-plus'
import Logo from "@/components/Logo.vue";
import {settings} from "@/setting.ts";

const isShowLoginForm = ref(true)

const formModel = ref<FormModel>({
  username: useUserStore().userState.username || '',
  password: '',
  confirmPassword: ''
})

const rulesForLogin = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
}
const rulesForRegister = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '用户名必须是4-16位字母、数字、\\或-组成', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {
      validator: (rule: any, value: string, callback: Function) => {
        console.log(rule)
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
const loginFormRef = ref()
const registerFormRef = ref()

const logging = ref(false)

/**
 * 登录
 */
function login() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      logging.value = true
      useUserStore().login(formModel.value).then(() => {
        router.push({path: '/'}).then(() => {
          ElNotification({
            title: 'Hello',
            message: `${getTimeOfDay()}好，${useUserStore().userState.username}！`,
            icon: SuccessFilled,
            showClose: true,
            type: 'success'
          })
        })
      }).catch((reason) => {
        console.log(reason)
        ElMessage.error(reason.message)
      }).finally(() => {
        logging.value = false
      })
    }
  })
}

const registering = ref(false)

/**
 * 注册
 */
function register() {
  registerFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      registering.value = true
      useUserStore().register(formModel.value).then(() => {
        router.push({path: '/'}).then(() => {
          ElNotification({
            message: `${getTimeOfDay()}好，${useUserStore().userState.username}！`,
            icon: SuccessFilled,
            showClose: false,
          })
        })
      }).catch((reason) => {
        if (reason?.message) {
          ElMessage.error(reason.message)
        }
      }).finally(() => {
        registering.value = false
      })
    }
  })
}

const centerDialogVisible = ref(false)

</script>

<template>
  <div id="login_container">
    <div class="part">
      <logo/>
      <el-row>
        <h1 class="gradient-text"
            style="color: #2e2929; font-size: 100px; font-weight: bold; width: 800px; line-height: initial; margin-top: 100px">
          你好，欢迎来到{{ settings.companyName }}
        </h1>
      </el-row>
      <el-row>
        <div style="margin-top: 70px;">
          <el-button plain @click="centerDialogVisible = true" round size="large"
                     style="min-height: 45px;">
            <span style="font-family: 方正姚体,serif; font-weight: bolder; font-size: 20px">注册/登录</span>
          </el-button>
          <span v-if="true">
<!--      <el-popconfirm title="如果本机没有部署后端服务器，想要预览一下首页吗？"-->
            <!--                     @confirm="$router.push({path: '/home'});useUserStore().setToken('1234567');ElMessage('伪造了一个token。')"-->
            <!--                     cancel-button-text="算了吧"-->
            <!--                     confirm-button-text="好，去看看">-->
            <!--        <template #reference>-->
            <!--          <el-button type="warning" round style="margin-left: 20px">注意</el-button>-->
            <!--        </template>-->
            <!--      </el-popconfirm>-->
    </span>
        </div>
      </el-row>
    </div>
    <el-dialog
        v-model="centerDialogVisible"
        width="500"
        align-center
        :close-on-click-modal="false"
    >
      <!-- 登录 -->
      <el-form class="login_form" v-show="isShowLoginForm" :rules="rulesForLogin" :model="formModel"
               ref="loginFormRef">
        <h1 style="margin-bottom: 20px">登录</h1>
        <el-form-item prop="username">
          <el-input clearable placeholder="请输入用户名" type="text" v-model="formModel.username">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input clearable show-password placeholder="请输入密码" type="password"
                    v-model="formModel.password">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex; width: 100%; justify-content: space-between;">
            <el-button style=" width: 40%" type="primary" @click="login()" :loading="logging">登录</el-button>
            <el-button style=" width: 40%" @click="()=>{isShowLoginForm = false; loginFormRef?.resetFields()}">
              <span style="font-family: 方正姚体,serif">没账号？去注册</span>
              <el-icon>
                <Right/>
              </el-icon>
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <!-- 注册 -->
      <el-form class="login_form" v-show="!isShowLoginForm" :rules="rulesForRegister" :model="formModel"
               ref="registerFormRef">
        <h1 style="margin-bottom: 20px">注册</h1>
        <el-form-item prop="username">
          <el-input clearable placeholder="请输入用户名" type="text" v-model="formModel.username">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input clearable show-password placeholder="请输入密码" type="password"
                    v-model="formModel.password"
                    @change="registerFormRef?.validateField('confirmPassword').then(()=>{}).catch(()=>{})">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input clearable show-password placeholder="请再次输入密码" type="password"
                    v-model="formModel.confirmPassword" ref="confirmPasswordRef">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex; width: 100%; justify-content: space-between;">
            <el-button style=" width: 40%" type="primary" @click="register()" :loading="registering">注册</el-button>
            <el-button style="width: 40%" @click="()=>{isShowLoginForm = true; registerFormRef?.resetFields()}">
              <span style="font-family: 方正姚体,serif">去登录</span>
              <el-icon>
                <Right/>
              </el-icon>
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
#login_container {
  height: 100vh;
  background: url("@/assets/login/背景.png") no-repeat;
  background-size: cover;

  .part {
    height: 100%;
    padding-left: 120px;
  }
}

</style>
